package com.example.jetpack.paging3

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ProgressBar
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.jetpack.MyService
import com.example.jetpack.R
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class PagingMainActivity : AppCompatActivity() {

    private val viewModel by lazy { ViewModelProvider(this).get(MainViewModel::class.java) }
    private val repoAdapter = RepoAdapter()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_paging_main)
        val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
        val progressbar = findViewById<ProgressBar>(R.id.progress_bar)

        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = repoAdapter.withLoadStateFooter(FootAdapter{repoAdapter.retry()})

        lifecycleScope.launch {
            viewModel.getPagingData().collectLatest {
                repoAdapter.submitData(it)
            }
        }
        repoAdapter.addLoadStateListener {
            when(it.refresh){
                is LoadState.NotLoading -> {
                    progressbar.visibility = View.INVISIBLE
                    recyclerView.visibility = View.VISIBLE
                }
                is LoadState.Loading -> {
                    progressbar.visibility = View.VISIBLE
                    recyclerView.visibility = View.INVISIBLE
                }
                is LoadState.Error -> {
                    val state  = it.refresh as LoadState.Error
                    progressbar.visibility = View.INVISIBLE
                    Toast.makeText(this,"Load Error: ${state.error.message}",Toast.LENGTH_SHORT).show()
                }
            }
        }
        startService(Intent(this,MyService::class.java))
    }
}